import { Card, Col, Pagination, Row, Tag, Table, message } from 'antd'
import React, { useEffect, useState } from 'react'
import type { DataNode, TreeProps } from 'antd/es/tree';
import { Tree } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { reqGetDoctors, reqGetHospitalDepartments, reqGetHospitalSchedule } from '@/api/hospital/hospitalList';
import { useParams } from 'react-router';
import { Department, DoctorItem, ScheduleItem } from '@/api/hospital/hospitalList/model/hospitalListTypes';

export default function HospitalSchedule() {
  //声明科室状态
  let [departments, setDepartments] = useState<Department[]>([]);
  //展开科室 depcode 的状态
  let [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  //选中二级科室的 id 状态
  let [depcode, setDepcode] = useState<string>('');
  //定义状态表示排班规则
  let [schedules, setSchedules] = useState<ScheduleItem[]>([]);
  //定义与分页相关的状态
  let [current, setCurrent] = useState<number>(1)
  let [total, setTotal] = useState<number>(0)
  let [pageSize, setPageSize] = useState<number>(5);
  //定义医生的状态
  let [doctors, setDoctors] = useState<DoctorItem[]>([]);
  //日期状态
  let [workDate, setWorkDate] = useState<string>('');
  //科室名称状态
  let [depname, setDepname] = useState<string>('');
  //医院名称状态
  let [hosname, setHosname] = useState<string>('');

  //定义表格的结构
  let columns: ColumnsType<DoctorItem> = [
    {
      title: '序号',
      render: (_, record, index) => index + 1
    },
    {
      title: '职称',
      dataIndex: 'title'
    },
    {
      title: '号源时间',
      dataIndex: 'workDate'
    },
    {
      title: '总预约数',
      dataIndex: 'reservedNumber'
    },
    {
      title: '剩余预约数',
      dataIndex: 'availableNumber'
    },
    {
      title: '挂号费',
      dataIndex: 'amount'
    },
    {
      title: '擅长技能',
      dataIndex: 'skill'
    },
  ];

  //从 url 中获取 hoscode 参数
  let { hoscode } = useParams();

  useEffect(() => {
    (async () => {
      //获取科室的信息
      let departments = await reqGetHospitalDepartments(hoscode as string);
      //使一级科室不可点
      let newDepartments = departments.map(item => {
        return { ...item, disabled: true };
      });
      setDepartments(newDepartments);
      //获取所有一级科室的 depcode
      let expandedKeys = departments.map(item => item.depcode);
      setExpandedKeys(expandedKeys);
      //获取第一个一级科室中第一个二级科室的 depcode
      let depcode = (departments[0].children as Department[])[0].depcode;
      let depname = (departments[0].children as Department[])[0].depname;

      //更新状态
      setDepcode(depcode);
      setDepname(depname);
    })()
  }, []);

  useEffect(() => {
    (async () => {
      //判断
      if (!depcode) return;
      try {
        //发送请求获取医院科室的排班规则
        let schedules = await reqGetHospitalSchedule({
          page: current,
          limit: pageSize,
          hoscode: hoscode as string,
          depcode: depcode
        });
        //更新状态
        setSchedules(schedules.bookingScheduleList);
        //更新数据的总数状态
        setTotal(schedules.total);
        //更新医院名称状态
        setHosname(schedules.baseMap.hosname);
        //获取第一个排班的日期
        let workDate = schedules.bookingScheduleList[0].workDate;
        //更新日期状态
        setWorkDate(workDate);
      } catch (e) {
        message.error('请求失败~~');
        //清空医生列表
        setDoctors([]);
        //workDate 更新
        setWorkDate('');
      }
    })();
  }, [depname, depcode, current, pageSize]);

  useEffect(() => {
    (async () => {
      //根据日期获取排班医生
      //判断排班日期
      if (!workDate) return;
      //获取医生的信息
      let doctors = await reqGetDoctors({
        workDate: workDate,
        hoscode: hoscode as string,
        depcode: depcode
      });
      //更新医生的状态
      setDoctors(doctors);
    })()
  }, [workDate])

  return (
    <Card>
      {/* 顶部路径导航 */}
      <div>选择：{hosname} / {depname} / {workDate}</div>
      <div className="h-20"></div>
      {/* 内容 */}
      <Row gutter={20}>
        <Col span={6}>
          <div style={{ border: 'solid 1px #ddd', height: 400, overflowY: 'scroll' }}>
            <Tree
              expandedKeys={expandedKeys}
              selectedKeys={[depcode]}
              onSelect={async (selectedKeys, info: any) => {
                // console.log(info);
                let depcode = info.node.depcode;
                let depname = info.node.depname;
                //更新状态
                setDepcode(depcode);
                setDepname(depname);
              }}
              treeData={departments as []}
              fieldNames={{
                title: 'depname',
                key: 'depcode'
              }}
            />
          </div>
        </Col>
        <Col span={18}>
          {/* 排班规则信息 */}
          <div>
            {
              schedules.map(item => {
                return <Tag
                  key={item.workDate}
                  color={item.workDate === workDate ? "success" : ''}
                  onClick={async () => {
                    //切换日期
                    setWorkDate(item.workDate);
                  }}
                >
                  <div>{item.workDate} {item.dayOfWeek}</div>
                  <div>{item.availableNumber} / {item.reservedNumber}</div>
                </Tag>
              })
            }
          </div>
          <div className="h-20"></div>
          {/* 分页结构 */}
          <Pagination
            current={current}
            total={total}
            pageSize={pageSize}
            showSizeChanger
            onChange={(page, pageSize) => {
              //更新状态
              setCurrent(page);
              setPageSize(pageSize);
            }}
          />
          <div className="h-20"></div>
          {/* 表格结构 */}
          <Table rowKey={'id'} columns={columns} dataSource={doctors} bordered pagination={false} />
        </Col>
      </Row>
    </Card>
  )
}
